package com.paypalpay.controller.interfaces;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.paypalpay.entity.common.UnifiedOrderPackages;
import com.paypalpay.external.entity.mcc.response.ResponseMcc;
import com.paypalpay.external.entity.open.request.RequestOpen;
import com.paypalpay.external.entity.open.request.RequestOpenData;
import com.paypalpay.external.entity.open.response.ResponseOpen;
import com.paypalpay.external.entity.open.response.ResponseOpenData;
import com.paypalpay.external.entity.open.response.ResponseOpenTradeData;
import com.paypalpay.external.utils.UtilsInterfacesPackage;
import com.paypalpay.pojo.Constant;
import com.paypalpay.service.PartnerService;
import com.paypalpay.service.SequenceService;
import com.paypalpay.service.UnifiedOrderPackagesService;
import com.paypalpay.turntointerfaceservice.TurnToOpenService;
import com.paypalpay.util.wx.MD5;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Demo 开通流量套餐
 *
 * @author lm
 * @date 2018/08/31
 */
@RestController
public class OpenDevicePackageController {
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private UnifiedOrderPackagesService unifiedOrderPackagesService;
    @Autowired
    PartnerService partnerService;

    private String token = "yv8JXeTTfqyedLcU2LAqHUTKtYA4G1kz";
    // 获取设备流量套餐列表
    private String tradeType = "F0004";

    @CrossOrigin
    @RequestMapping(value = "/openPackages", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "领科商城详情页", response = ResponseMcc.class)
    public String open(@ApiParam @RequestBody RequestOpen requestOpen) {
        String requestStr = JSON.toJSONString(requestOpen);
        System.out.println("前端请求报文是：" + requestStr);
        // 1，生成流水号
        String ConnSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();

        requestOpen = JSONArray.parseObject(requestStr, RequestOpen.class);
        String requestSign = requestOpen.getSign();
        if (requestOpen.getSign() == null) {
            System.out.println("请求报文不合法:sign为空");
            String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
            return jsonString;
        } else {
            System.out.println("请求的签名是：" + requestSign);
            RequestOpenData requestData = requestOpen.getData();
            if (requestOpen.getData() == null) {
                System.out.println("请求报文不合法:data为空");
                String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                return jsonString;
            } else {
                String connSeqNo = requestData.getConnSeqNo();
                String token = requestData.getToken();
                String partnerCode = requestData.getPartnerCode();
                String secret = partnerService.findSecretByPartnerCode(partnerCode);
                String tradeTime = requestData.getTradeTime();
                if (requestData.getTradeData() == null) {
                    System.out.println("请求报文不合法:TradeData为空");
                    String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                    return jsonString;
                } else {
                    //将报文中有用的信息取出来存下来
                    String deviceId = requestData.getTradeData().getDeviceId();
                    String deviceType = requestData.getTradeData().getDeviceType();
                    String orderId = requestData.getTradeData().getOrderId();

                    if (deviceId == null || deviceId.length() <= 0 || deviceType == null || deviceType.length() <= 0 || orderId == null || orderId.length() <= 0) {
                        System.out.println("请求报文不合法:参数不全！");
                        String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                        return jsonString;
                    } else {
                        // 将请求体json转成String
                        String str = JSON.toJSONString(requestData);
                        // 将Str拿去计算签名
                        String sign = utils.calculateSignature(str);
                        System.out.println("计算的签名是：" + sign);
                        //参数是齐全的
                        // 验证签名：
                        if (!requestSign.equalsIgnoreCase(sign)) {
                            // 如果收到的签名跟算出的签名相同才可以回复正确的报文
                            String jsonString = utils.publicMessage(ConnSeqNo, tradeTime, partnerCode, token, tradeType);
                            return jsonString;
                        } else {
                            //签名通过的
                            //1，现在我们先去数据库查询一下当前订单是不是未开通的
                            String isOpen = unifiedOrderPackagesService.getIsOpenByOrderIdanddeviceId(deviceId, orderId);

                            if (isOpen.equals("1")) {
                                //说明已经是开通状态，回复报文
                                String jsonString = utils.publicIsopen(ConnSeqNo, tradeTime, partnerCode, token, tradeType);
                                return jsonString;
                            } else {
                                //2,现在去北京开通套餐流量
                                TurnToOpenService openService = new TurnToOpenService();
                                UnifiedOrderPackages user = openService.openMonthlyPackage(partnerCode, deviceType, orderId, secret);
                                System.out.println("到这里说明拿到北京给回来的数据了：" + user.getRetCode());
                                if (user == null) {
                                    ResponseOpenData data = new ResponseOpenData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(tradeTime);
                                    data.setTradeRstCode(Integer.parseInt(user.getRetCode()));
                                    data.setTradeRstMessage(user.getResultInfo());

                                    ResponseOpen responseOpen = new ResponseOpen();
                                    responseOpen.setData(data);
                                    responseOpen.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                    // 返回给调用者的报文
                                    String jsonString = JSON.toJSONString(responseOpen);
                                    System.out.println("响应报文：" + jsonString);
                                    return jsonString;

                                } else {
                                    if (true == Constant.RET_CODE_0000.equalsIgnoreCase(user.getRetCode())) {

                                        //3,现在去数据库更新isopen这个字段
                                        user.setOrderId(user.getOrderId());
                                        user.setOrderStartDate(user.getOrderStartDate());
                                        user.setOrderExpireDate(user.getOrderExpireDate());
                                        user.setIsOpen("1");
                                        user.setUpdateTime(tradeTime);
                                        unifiedOrderPackagesService.updateIsOpenByorderId(user);
                                        System.out.println("到这里说明isopen更新完成：" + user.getOrderId());

                                        //4，现在开始拼接回报前端的报文
                                        ResponseOpenTradeData tradeData = new ResponseOpenTradeData();
                                        tradeData.setOrderId(user.getOrderId());
                                        tradeData.setOrderStartDate(user.getOrderStartDate());
                                        tradeData.setOrderExpireDate(user.getOrderExpireDate());

                                        ResponseOpenData data = new ResponseOpenData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(tradeTime);
                                        data.setTradeRstCode(1000);
                                        data.setTradeRstMessage("成功");
                                        data.setTradeData(tradeData);

                                        ResponseOpen responseOpen = new ResponseOpen();
                                        responseOpen.setData(data);
                                        responseOpen.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        // 返回给调用者的报文
                                        String jsonString = JSON.toJSONString(responseOpen);
                                        System.out.println("响应报文：" + jsonString);
                                        return jsonString;

                                    } else {

                                        ResponseOpenData data = new ResponseOpenData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(tradeTime);
                                        data.setTradeRstCode(Integer.parseInt(user.getRetCode()));
                                        data.setTradeRstMessage(user.getResultInfo());

                                        ResponseOpen responseOpen = new ResponseOpen();
                                        responseOpen.setData(data);
                                        responseOpen.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        // 返回给调用者的报文
                                        String jsonString = JSON.toJSONString(responseOpen);
                                        System.out.println("响应报文：" + jsonString);
                                        return jsonString;

                                    }


                                }
                            }
                        }

                    }
                }
            }
        }
    }
}

